package com.java.forum.c_service;

import com.java.forum.a_entity.Collection;
import com.java.forum.a_entity.Subscribe;
import com.java.forum.a_entity.User;
import com.java.forum.b_mapper.CollectionMapper;
import com.java.forum.b_mapper.PostMapper;
import com.java.forum.b_mapper.SubscribeMapper;
import com.java.forum.b_mapper.UserMapper;
import com.java.forum.g_exception.Exceptions;
import com.java.forum.g_exception.ServiceException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class UserServiceImpl implements UserService {
    private UserMapper userMapper;
    private SubscribeMapper subscribeMapper;
    private CollectionMapper collectionMapper;
    private PostMapper postMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setSubscribeMapper(SubscribeMapper subscribeMapper) {
        this.subscribeMapper = subscribeMapper;
    }

    @Autowired
    public void setCollectionMapper(CollectionMapper collectionMapper) {
        this.collectionMapper = collectionMapper;
    }

    @Autowired
    public void setPostMapper(PostMapper postMapper) {
        this.postMapper = postMapper;
    }

    @Override
    public User login(Integer uid, String password) {
        User user = userMapper.getUserByUid(uid);
        if (user == null) throw new ServiceException(Exceptions.UserNotFoundException);
        password = getSHA256Password(password, user.getSalt());
        if (!password.equals(user.getPassword())) throw new ServiceException(Exceptions.UserPasswordNotMatch);
        return user;
    }

    @Override
    public Integer register(User user) {
        String password = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        user.setSalt(salt);
        String newPassword = getSHA256Password(password, salt);
        user.setPassword(newPassword);
        user.setGender(2);//默认未设置
        user.setAvatar("../../static/logo.png");
        Integer res = userMapper.insertUser(user);
        if (res != 1) throw new ServiceException(Exceptions.UserInsertException);
        return user.getUid();//返回id值
    }

    @Override
    public String resetPassword(Integer uid, String email) {
        User user = userMapper.getUserByUid(uid);
        if (user == null) throw new ServiceException(Exceptions.UserNotFoundException);
        if (!email.equals(user.getEmail())) throw new ServiceException(Exceptions.UserMailNotMatch);
        String newPassword = generateRandomString();
        String encrypt = getSHA256Password(newPassword, user.getSalt());
        Integer res = userMapper.updateUserPassword(encrypt, user.getUid());
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException);
        return newPassword;
    }

    @Override
    public User getUserInfo(Integer uid) {
        User user = userMapper.getUserByUid(uid);
        if (user == null) throw new ServiceException(Exceptions.UserNotFoundException);
        return user;
    }

    @Override
    public void updateUserInfo(User user) {
        Integer res = userMapper.updateUserInfo(user);
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException);
    }

    @Override
    public void updateUserEmail(User user, String password, String email) {
        String pwd = user.getPassword();
        String encrypt = getSHA256Password(password, user.getSalt());
        if (!pwd.equals(encrypt)) throw new ServiceException(Exceptions.UserPasswordNotMatch);
        user.setEmail(email);
        Integer res = userMapper.updateUserInfo(user);
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException);
    }

    @Override
    public void updatePassword(String oldPassword, String newPassword, User user) {
        String old = getSHA256Password(oldPassword, user.getSalt());
        if (!old.equals(user.getPassword())) throw new ServiceException(Exceptions.UserPasswordNotMatch);
        String newP = getSHA256Password(newPassword, user.getSalt());
        Integer res = userMapper.updateUserPassword(newP, user.getUid());
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException);

    }

    @Override
    public Integer SubscribeUser(Subscribe subscribe) {
        if (subscribeMapper.IsSubscribe(subscribe.getGUid(), subscribe.getBUid()) != null) {
            throw new ServiceException(Exceptions.SubscribeInsertException);
        }
        subscribe.setDate(new Date());
        Integer res = subscribeMapper.InsertSubscribe(subscribe);
        if (res != 1) throw new ServiceException(Exceptions.SubscribeInsertException);
        return subscribe.getSid();
    }

    @Override
    public void UnSubscribeUser(Subscribe subscribe) {
        Integer res = subscribeMapper.DeleteSubscribe(subscribe);
        if (res < 1) throw new ServiceException(Exceptions.SubscribeDeleteException);
    }

    @Override
    public Integer isSubscribe(int GUid, int BUid) {
        Subscribe subscribe = subscribeMapper.IsSubscribe(GUid, BUid);
        if (subscribe == null) {
            return 0;
        }
        return 1;
    }

    @Override
    public List<Subscribe> getSubscribeList(int GUid) {
        return subscribeMapper.getSubscribeList(GUid);
    }

    @Override
    public List<Subscribe> getBeSubscribedList(int BUid) {
        return subscribeMapper.getBeSubscribedList(BUid);
    }

    @Override
    public Integer CollectPost(Collection collection) {
        if (collectionMapper.IsCollected(collection.getPid(), collection.getUid()) != null) {
            throw new ServiceException(Exceptions.CollectionInsertException);
        }
        collection.setDate(new Date());
        Integer res = collectionMapper.InsertCollection(collection);
        if (res != 1) throw new ServiceException(Exceptions.CollectionInsertException);
        Integer res1 = postMapper.PostAddCollections(collection.getPid());
        if (res1 != 1) throw new ServiceException(Exceptions.CollectionInsertException);
        return collection.getCoid();
    }

    @Override
    public void UnCollectPost(Collection collection) {
        Integer res = collectionMapper.DeleteCollection(collection);
        if (res < 1) throw new ServiceException(Exceptions.CollectionDeleteException);
        Integer res1 = postMapper.PostRemoveCollections(collection.getPid());
        if (res1 != 1) throw new ServiceException(Exceptions.CollectionDeleteException);
    }

    @Override
    public Integer isCollect(int pid, int uid) {
        Collection collection = collectionMapper.IsCollected(pid, uid);
        if (collection == null) {
            return 0;
        }
        return 1;
    }

    @Override
    public List<Collection> getCollectionList(int uid) {
        return collectionMapper.getCollectionByUid(uid);
    }


    //算法加密
    private String getSHA256Password(String password, String salt) {
        return new SimpleHash("SHA-256", password, salt, 20).toString();
    }

    private String generateRandomString() {
        String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
                "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        StringBuilder builder = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            builder.append(chars[x % 0x3E]);
        }
        return builder.toString();

    }
}
